package com.hetang.maijiayun.adaptertools.utils;

import com.alibaba.fastjson.JSON;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/9/16.
 * json 帮助类
 */
public class JsonTools {
    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(JsonTools.class);

    /**
     * 对象转换为json
     *
     * @param value
     * @return
     */
    public static String createJsonString(Object value) {
        String str = JSON.toJSONString(value);
        return str;
    }

    /**
     * json 转换为对象
     *
     * @param jsonString
     * @param clazz
     * @return
     */
    public static <T> T getObject(String jsonString, Class<T> clazz) {
        T t = null;
        try {
            t = JSON.parseObject(jsonString, clazz);
        } catch (Exception e) {
            LOGGER.error("JSON转换成对象失败!!{}{}", jsonString, e);
        }
        return t;
    }

    /**
     * json转换为List<Object>
     *
     * @param jsonString
     * @param clazz
     * @return
     */
    public static <T> List<T> getObjects(String jsonString, Class<T> clazz) {
        List<T> list = new ArrayList<T>();
        try {
            list = JSON.parseArray(jsonString, clazz);
        } catch (Exception e) {
            LOGGER.error("JSON转换成对象失败!!{}{}", jsonString, e);
        }
        return list;
    }

    /**
     * json转换为List<Map<String, Object>>
     *
     * @param jsonString
     * @return
     */
    public static List<Map<String, Object>> listKeyMaps(String jsonString) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        try {
            list = JSON.parseObject(jsonString, new TypeReference<List<Map<String, Object>>>() {
            }.getType());
        } catch (Exception e) {
            LOGGER.error("JSON转换成对象失败!!{}{}", jsonString, e);
        }
        return list;
    }
}
